<template>
  <div class="corse-section">
    <el-card>
      <div slot="header" class="card-header">
        {{ course.courseName }}
        <el-button type="primary" @click="handleShowAddSection"
          >添加阶段</el-button
        >
      </div>
      <el-tree
        :data="sections"
        :props="defaultProps"
        draggable
        v-loading="isLoading"
        :allow-drop="handleAllowDrop"
        @node-drop="handleSort"
      >
        <div slot-scope="{ node, data }" class="inner">
          <span>{{ node.label }}</span>
          <span v-if="data.sectionName" class="action">
            <el-button @click.stop="handleEditSrctionShow(data)"
              >编辑</el-button
            >
            <el-button type="primary" @click.stop="handleShowAddLesson(data)"
              >添加课时</el-button
            >
            <el-select
              class="select-status"
              v-model="data.status"
              placeholder="请选择"
              @change="handleSectionStatusChange(data)"
            >
              <el-option label="已隐藏" :value="0"></el-option>
              <el-option label="待更新" :value="1"></el-option>
              <el-option label="已更新" :value="2"></el-option>
            </el-select>
          </span>
          <span v-else class="action">
            <el-button @click="handleShowEditLesson(data, node.parent.data)"
              >编辑</el-button
            >
            <el-button type="success" @click="$router.push({
              name: 'course-video',
              params: {
                courseId
              },
              query: {
                sectionId: node.parent.id,
                lessonId: data.id
              }
            })"
              >上传视频</el-button
            >
            <el-select
              class="select-satatus"
              v-model="data.status"
              placeholder="请选择"
              @change="handleLessonStatusChange(data)"
            >
              <el-option label="已隐藏" :value="0"></el-option>
              <el-option label="待更新" :value="1"></el-option>
              <el-option label="已更新" :value="2"></el-option>
            </el-select>
          </span>
        </div>
      </el-tree>
    </el-card>

    <el-dialog title="添加课程阶段" :visible.sync="isAddSectionShow">
      <el-form ref="section-form" :model="section" label-width="80px">
        <el-form-item label="课程名称">
          <el-input
            :value="course.courseName"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input v-model="section.sectionName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input
            v-model="section.description"
            type="textarea"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="章节排序" prop="orderNum">
          <el-input-number
            v-model="section.orderNum"
            autocomplete="off"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddSectionShow = false">取 消</el-button>
        <el-button @click="handleAddSection" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加课时" :visible.sync="isAddLessonShow">
      <el-form ref="lesson-form" :model="section" label-width="100px">
        <el-form-item label="课程名称">
          <el-input
            :value="course.courseName"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input v-model="lesson.sectionName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课时名称" prop="theme">
          <el-input
            v-model="lesson.theme"
            type="textarea"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="时长" prop="duration">
          <el-input-number v-model="lesson.duration" autocomplete="off">
            <template slot="append">分钟</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="是否开放试听" prop="isFree">
          <el-switch v-model="lesson.isFree"></el-switch>
        </el-form-item>
        <el-form-item label="课时排序" prop="orderNum">
          <el-input-number
            v-model="lesson.orderNum"
            type="textarea"
            autocomplete="off"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddLessonShow = false">取 消</el-button>
        <el-button @click="handleAddLesson" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getSectionAndLesson,
  saveOrUpdateSection,
  getSectionById
} from '@/services/course-section'
import { getCourseById } from '@/services/course'
import { Form } from 'element-ui'
import { saveOrUpdateLesson } from '@/services/course-lesson'

export default Vue.extend({
  name: 'CourseSection',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    const defaultProps = {
      children: 'lessonDTOS',
      label (data: any) {
        return data.sectionName || data.theme
      }
    }

    const section = {
      courseId: this.courseId,
      sectionName: '',
      description: '',
      orderNum: 0,
      status: 0
    }

    const lesson = {
      courseId: this.courseId,
      sectionId: undefined,
      sectionName: '',
      thtme: '',
      duration: 0,
      isFree: false,
      orderNum: 0,
      status: 0
    }

    return {
      sections: [],
      course: {},
      defaultProps,
      section,
      lesson,
      isAddSectionShow: false,
      isAddLessonShow: false,
      isLoading: false
    }
  },
  created () {
    this.loadSections()
    this.loadCourse()
  },
  methods: {
    async loadCourse () {
      const { data } = await getCourseById(this.courseId)
      this.course = data.data
    },
    async loadSections () {
      const { data } = await getSectionAndLesson(this.courseId)
      this.sections = data.data
    },
    handleShowAddSection () {
      this.section = {
        courseId: this.courseId,
        sectionName: '',
        description: '',
        orderNum: 0,
        status: 0
      }
      this.isAddSectionShow = true
    },
    async handleAddSection () {
      await saveOrUpdateSection(this.section)
      this.loadSections()
      this.isAddSectionShow = false;
      (this.$refs['section-form'] as Form).resetFields()
      this.$message.success('操作成功')
    },
    async handleEditSectionShow (section: any) {
      const { data } = await getSectionById(section.id)
      this.section = data.data
      this.isAddSectionShow = true
    },
    async handleSectionStatusChange (section: any) {
      await saveOrUpdateSection(section)
      this.$message.success('操作成功')
    },
    async handleLessonStatusChange (lesson: any) {
      //
      await saveOrUpdateLesson(lesson)
      this.$message.success('操作成功')
    },
    handleShowAddlesson (data: any) {
      this.lesson = {
        courseId: this.courseId,
        sectionId: data.id,
        sectionName: data.sectionName,
        thtme: '',
        duration: 0,
        isFree: false,
        orderNum: 0,
        status: 0
      }
      this.isAddLessonShow = true
    },
    async handleAddLesson () {
      await saveOrUpdateLesson(this.lesson)
      this.$message.success('操作成功')
      this.loadSections()
      this.isAddLessonShow = false
    },
    handleShowEditLesson (lesson: any, section: any) {
      this.lesson = lesson
      this.lesson.sectionName = section.sectionName
      this.isAddLessonShow = true
    },
    handleAllowDrop (draggingNode: any, dropNode: any, type: any) {
      return (
        draggingNode.data.sectionId === dropNode.data.sectionId &&
        type !== 'inner'
      )
    },

    async handleSort (dragNode: any, dropNode: any, type: any, event: any) {
      this.isLoading = true
      try {
        await Promise.all(
          dropNode.parent.childNodes.map((item: any, index: number) => {
            if (dragNode.data.lessonDTOS) {
              return saveOrUpdateSection({
                id: item.data.id,
                orderNum: index + 1
              })
            } else {
              return saveOrUpdateLesson({
                id: item.data.id,
                orderNum: index + 1
              })
            }
          })
        )
        this.$message.success('排序成功')
      } catch (err) {
        this.$message.error('排序失败')
      }
      this.isLoading = false
    }
  }
})
</script>
<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
}
.inner {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}
::v-deep .el-tree-node__content {
  height: auto;
}
.select-status {
  max-width: 100px;
  margin-left: 8px;
}
</style>
